<template>
  <!-- 头部标题 -->
  <BasicInformation :title="title" @action="handleAction" :primary-actions="mainActions"></BasicInformation>

  <div class="add">
    <div class="common-layout">
      <el-container>
        <el-main>
          <el-row>
            <el-col :span="24">
              <div class="grid-content ep-bg-purple">
                <h4>基本信息</h4>
                <el-form :inline="true" :model="inventoryCheckOrder" :rules="rules" status-icon ref="formRef">
                  <el-form-item label="单据编号" prop="code">
                    <el-input
                        v-model="inventoryCheckOrder.code"
                        style="width: 240px"
                        placeholder="请输入单据编号"
                        clearable
                        :disabled="true"
                    />
                  </el-form-item>
                  <!-- 客户 -->
                  <el-form-item label="盘点员" prop="checkManId">
                    <el-select
                        v-model="inventoryCheckOrder.checkManId"
                        placeholder="请选择盘点员"
                        style="width: 240px"
                        clearable
                        filterable
                    >
                      <el-option
                          v-for="user in userList"
                          :key="user.id"
                          :label="`${user.name}`"
                          :value="user.id"
                      />
                    </el-select>
                  </el-form-item>

                  <!-- 报价日期 -->
                  <el-form-item label="单据日期" prop="orderDate">
                    <el-date-picker
                        v-model="inventoryCheckOrder.orderDate"
                        type="date"
                        placeholder="请选择日期"
                        value-format="YYYY-MM-DD"
                        :disabled-date="disabledDate"
                    />
                  </el-form-item>
                  <!-- 业务员 -->
                  <el-form-item label="盘点仓库" prop="storeId">
                    <el-select style="width: 220px"
                               @change ="storeChange"
                        v-model="inventoryCheckOrder.storeId"
                        placeholder="请选择仓库"
                        clearable
                    >
                      <el-option
                          v-for="store in storeList"
                          :key="store.id"
                          :label="`${store.code} - ${store.name}`"
                          :value="store.id"
                      />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="盘点任务" prop="checkTask">
                    <el-input
                        v-model="inventoryCheckOrder.checkTask"
                        style="width: 240px"
                        placeholder="请输入盘点任务"
                    />
                  </el-form-item>

                  <!-- 部门 -->
                  <el-form-item label="部门" prop="deptId">
                    <el-select
                        v-model="inventoryCheckOrder.deptId"
                        placeholder="请选择部门"
                        style="width: 240px;"
                        clearable
                    >
                      <el-option
                          v-for="dept in deptList"
                          :key="dept.id"
                          :label="dept.name"
                          :value="dept.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
            </el-col>
          </el-row>
        </el-main>
      </el-container>
    </div>
  </div>
  <div>
    <div class="toolbar">
      <el-button type="primary">商品信息</el-button>
      <el-button @click="addDetailRow">继续添加</el-button>
      <el-button type="danger" @click="deleteSelectedRows">删除选中行</el-button>
    </div>

    <!-- 商品信息表格 -->
    <el-table :data="inventoryCheckDetail" border style="width: 100%" class="goods-table" @selection-change="newHHandleSelectionChange">
      <el-table-column type="selection" width="55" />
      <!-- 商品编码（带必填标识的下拉框） -->
      <el-table-column label="商品编码" width="150">
        <template #header>
          <span class="required-label">商品编码</span>
        </template>
        <template #default="scope">
          <el-select
              v-model="scope.row.goodsCode"
              placeholder="请选择商品"
              @change="handleGoodsChange(scope.row)"
              clearable
          >
            <el-option
                v-for="item in goodsList"
                :key="item.code"
                :label="`${item.code} - ${item.name}`"
                :value="item.code"
            />
          </el-select>
        </template>
      </el-table-column>

      <!-- 商品名称 -->
      <el-table-column label="商品名称" width="180">
        <template #default="scope">{{ scope.row.goodsName || '-' }}</template>
      </el-table-column>


      <!-- 即时库存 -->
      <el-table-column label="即时库存" width="100" align="center">
        <template #default="scope">{{ scope.row.stock || 0 }}</template>
      </el-table-column>

      <!-- 单位（带必填标识） -->
      <el-table-column label="单位" width="80" align="center">
        <template #header>
          <span class="required-label">单位</span>
        </template>
        <template #default="scope">{{ scope.row.unit || '件' }}</template>
      </el-table-column>

      <!-- 数量（带必填标识的输入框） -->
      <el-table-column label="盘点数" width="120" align="center">
        <template #header>
          <span class="required-label">盘点数</span>
        </template>
        <template #default="scope">
          <el-input-number
              @change="changeNum(scope.row)"
              v-model="scope.row.checkNum"
              controls-position="right"
              style="width: 100px"
          >
          </el-input-number>
        </template>
      </el-table-column>


      <el-table-column label="盈亏数" width="120" align="center">
        <template #default="scope">{{ scope.row.phaseNum}}</template>
      </el-table-column>


      <el-table-column label="单位成本" width="120" align="center">
        <template #default="scope">{{ scope.row.singleCost || 0 }}</template>
      </el-table-column>

      <el-table-column label="总成本" width="120" align="center">
        <template #default="scope">{{ scope.row.sumCost || 0 }}</template>
      </el-table-column>


    </el-table>

  </div>
  <div class="total-summary">
    <div class="total-label">合计</div>
    <div class="total-amount">{{ formatTotal }}</div>
  </div>




</template>



<script setup lang="ts">
import { ref, reactive,withKeys ,watch,computed, onMounted} from 'vue';
import BasicInformation from '@/public-view/BasicInformation.vue';
import {ElInput, ElAutoResizer, ElTableV2, type FormInstance} from 'element-plus'

import { useRouter,useRoute } from 'vue-router';

import type { Goods } from '@/types/public-xs/Goods';

import type { Customer } from '@/types/public-xs/Customer';
import axios from 'axios';
import { ElMessageBox, ElMessage } from 'element-plus'

import type {InventoryLossDetail, InventoryProfitDetail} from "@/types/kc/InventoryCheck.ts";
import type {User} from "@/types/rs/User.ts";
import type {Department} from "@/types/rs/Department.ts";
import type {Store} from "@/types/basic/store.ts";
import request from "@/util/request.ts";

//销售出库单
let code=ref('')
//销售订单
let sourceCode=ref('')
let title=ref('盘点单')
let goodsList=ref<Goods[]>([])
let pageNo=ref(1)
let pageSize=ref(5)
let allPage=ref(0)
let router=useRouter()
//部门情况
let userList=ref<User[]>([])
let selectUser=async()=>{
  let response=await request.post('per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()

let deptList=ref<Department[]>([])
let selectDept=async()=>{
  let response=await request.post('per/dept/getAll')
  deptList.value=response.data.data
  console.log(deptList.value)
}
selectDept()

let storeList=ref<Store[]>([])
let selectStore=async()=>{
  let response=await request.post('basic/store/getAllStore')
  storeList.value=response.data.data
  console.log(storeList.value)
}
selectStore()
//商品查询条件
const queryConditions = reactive({
  combine: '',
  kid: ''
})
const changeNum = (inventoryCheckDetail:any) => {
  console.log(inventoryCheckDetail.checkNum)
  console.log(inventoryCheckDetail.stock)

  inventoryCheckDetail.phaseNum =  inventoryCheckDetail.checkNum - inventoryCheckDetail.stock
  console.log(inventoryCheckDetail.phaseNum)
  inventoryCheckDetail.sumCost =  parseFloat((inventoryCheckDetail.singleCost * inventoryCheckDetail.phaseNum).toFixed(2))
}

//填写信息区域的表单验证
const rules = reactive({
  checkManId: [{ required: true, message: '请选择盘点员', trigger: 'blur' ,type:'number'}],
  code: [{ required: true, message: '请选择单据编号', trigger: 'change' }],
  deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
  storeId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
  checkTask: [{ required: true, message: '填写盘点任务', trigger: 'change' }]
})
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}

// 修改handleAction方法
const handleAction = (action:string) => {
  switch(action) {
    case 'choose':
      // if (!outStoreOrder.value.cid) {
      //   ElMessage.warning('请先选择客户')
      //   return
      // }
      // dialogVisible.value = true
      // selectSaleOrderListByCid()  // 自动触发数据加载
      break
    case 'save-add':
      insertInventoryCheckOrder()
      break;
    case 'history':
      router.push('/home/inventoryCheck/page')
      break;



  }
}
async function fetchData(page: number) {
  try {
    const params = new URLSearchParams();
    params.append('pageNow', page.toString());
    params.append('pageSize', 100);
    params.append('combine', queryConditions.combine);
    params.append('kid', queryConditions.kid);

    let response = await request.post('basic/good/getGoodPage', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });
    goodsList.value = response.data.data.list.map((item: any) => ({
      id: item.id,
      code: item.code,
      name: item.name,
      unique: item.unique,
      tax: item.tax,
      stock: item.stock,
      kname: item.kname
    }));
    console.log(goodsList.value)
    allPage.value = response.data.data.total || 0;
  } catch (error) {
    ElMessage.error('获取商品数据失败');
    inventoryCheckDetail.value = [];
    allPage.value = 0;
    console.error('获取数据失败:', error);
  }
}
fetchData(1)




const mainActions = ref([
  {
    name: 'save',
    label: '保存',
    type: 'primary',
    icon: 'DocumentAdd'
  },
  {
    name: 'save-add',
    label: '保存新增',
    disabled: false
  },
  {
    name: 'audit',
    label: '审核',
    hidden: false
  },
  // {
  //   name: 'choose',
  //   label: '选择源单',
  //   hidden: false
  // },
  {
    name: 'history',
    label: '历史单据',
    badge: 3 // 角标数字
  }
])
let inventoryCheckOrder=ref({
  id:null,
  code:code.value,
  orderDate:new Date,
  checkTask:'',
  storeId:null,
  checkStatus:0,
  inventoryProfitCode:'',
  inventoryLossCode:'',
  typeId:8,
  checkManId: null,
  deptId:null,
  orderStatus: 0,
  createId: 1,
  createDate: new Date,
  updateId: 1,
  updateDate: new Date,
  isDelete: 0,
})

const inventoryCheckDetail = ref([{
  id: generateUUID(),
  inventoryCheckCode:'',
  goodId:0,
  goodsCode:'',
  stock:0,
  goodsName:'',
  unit:'',
  checkNum:0,
  phaseNum:0,
  singleCost:0,
  sumCost:0,
  isDelete:0,
  createId:1,
  createDate:new Date(),
  updateId:1,
  updateDate:new Date()
}])

const inventoryLossDetail = ref<InventoryLossDetail[]>([])

let inventoryLossOrder=ref({
  id:null,
  code:'',
  orderDate:new Date,
  orderStatus: 0,
  deptId:1,
  typeId:41,
  storeId:0,
  checkManId: 1,
  createId: 1,
  createDate: new Date,
  updateId: 1,
  updateDate: new Date,
  isDelete: 0,
})

let inventoryProfitOrder=ref({
  id:null,
  code:'',
  orderDate:new Date,
  orderStatus: 0,
  typeId:42,
  deptId:1,
  storeId:0,
  checkManId: 1,
  createId: 1,
  createDate: new Date,
  updateId: 1,
  updateDate: new Date,
  isDelete: 0,
})
const inventoryProfitDetail = ref<InventoryProfitDetail[]>([])


let addDetail=async(inventoryCheckCode:string)=>{
  for (const item of inventoryCheckDetail.value) {
//假设库存为10个
    let response= await request.post('kc/inventoryCheckDetail/insertInventoryCheckDetail',{
      ...item,
      inventoryCheckCode:inventoryCheckCode
    })
    //     let response= await axios({
    //   url:'kc/inventoryCheckDetail/insertInventoryCheckDetail',
    //   method:'post',
    //   data :{
    //     ...item,
    //     inventoryCheckCode:inventoryCheckCode
    //   }
    // })

    if(item.phaseNum>0){

      inventoryProfitDetail.value.push(
          {
            id: generateUUID(),
            inventoryProfitCode:inventoryProfitOrder.value.code,
            goodId:item.goodId,
            goodsCode:item.goodsCode,
            goodsName:item.goodsName,
            unit:item.unit,
            inventoryProfitNum:item.phaseNum,
            singleCost:item.singleCost,
            sumCost:100,
            isDelete:item.isDelete,
            createId:item.createId,
            createDate:new Date(),
            updateId:item.updateId,
            updateDate:new Date()
          }
      )
    }else if(item.phaseNum<0){
      inventoryLossDetail.value.push(
          {
            id: generateUUID(),
            inventoryLossCode:inventoryLossOrder.value.code,
            goodId:item.goodId,
            goodsCode:item.goodsCode,
            goodsName:item.goodsName,
            unit:item.unit,
            inventoryLossNum:Math.abs(item.phaseNum),
            singleCost:item.singleCost,
            sumCost:100,
            isDelete:item.isDelete,
            createId:item.createId,
            createDate:new Date(),
            updateId:item.updateId,
            updateDate:new Date()
          }
      )
    }
  }

}

//访问方法并获取单据编号
let getDocCode=async()=>{
  let response=await request.post('xs/counter/addCode',{docType:'PDD'})
  code.value=response.data.data
  inventoryCheckOrder.value.code = code.value
}
onMounted(async () => {
  await getDocCode()
})


//动态加载客户
let customerList=ref<Customer[]>([])
let selectCustomer=async()=>{
  let response=await request.post('basic/Customer/selectAllCustomer')
  customerList.value=response.data.data
  console.log(customerList.value)
}
selectCustomer()





function generateUUID() {
  const min = 100000000;
  const max = 999999999;
  return Math.floor(Math.random() * (max - min + 1)) + min;
}





//选中商品数据
const handleGoodsChange = async (row: any) => {
  const selected = goodsList.value.find(item => item.code === row.goodsCode)
  if (selected) {
    row.goodsName = selected.name
    row.goodId = selected.id;
    row.unit = selected.unique
    row.tax = selected.tax;
    row.kname = selected.kname
    calculateTaxPrice(row)
  } else {
    // 清空相关字段
    row.goodsName = ''
    row.unit = '件'
  }

  let response = await request({
    url: 'kc/StoreGoodSummary/selectKcStoreGoodBySidCid',
    method: 'get',
    params: {
      sid: inventoryCheckOrder.value.storeId,
      gid: row.goodId
    }
  })

  if (response.data.data) {
    row.stock = response.data.data.stock
    row.singleCost = response.data.data.singleCost
  }else{
    row.stock = 0
    row.singleCost=0
  }
  changeNum(row)
}

const newSelectedRows = ref<any[]>([])

// 处理选中行变化
const newHHandleSelectionChange = (selection: any[]) => {
  newSelectedRows.value = selection
}

const storeChange = async () => {
  for (const row of inventoryCheckDetail.value) {
    let response = await request({
      url: 'kc/StoreGoodSummary/selectKcStoreGoodBySidCid',
      method: 'get',
      params: {
        sid: inventoryCheckOrder.value.storeId,
        gid: row.goodId
      }
    })
  console.log(response.data.data)
    if (response.data.data) {
      row.stock = response.data.data.stock
      row.singleCost = response.data.data.singleCost
    }else{
      row.stock = 0
      row.singleCost = 0
    }
    changeNum(row)
  }
}

// 删除选中行方法（添加确认对话框）
const deleteSelectedRows = async () => {
  if (newSelectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的行')
    return
  }

  try {
    await ElMessageBox.confirm(
        `确定要删除选中的 ${newSelectedRows.value.length} 行吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )
    // 通过ID过滤实现删除
    const selectedIds = new Set(newSelectedRows.value.map(row => row.id))
    inventoryCheckDetail.value = inventoryCheckDetail.value.filter(row => !selectedIds.has(row.id))

    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.info('已取消删除')
  }
}


//价格校验
const validatePrice = (row:any) => {
  row.actualPrice = row.actualPrice.replace(/[^\d.]/g, '')
}

// 含税价计算
const calculateTaxPrice = (row:any) => {
  if (row.actualPrice && row.vatRate) {
    row.taxIncludedPrice = (row.actualPrice * (1 + row.vatRate/100)).toFixed(2)
  }
}



//格式化金额显示
const totalAmount = computed(() => {
  return inventoryCheckDetail.value.reduce((sum, row) => {
    const price = Number(row.singleCost) || 0
    const quantity = Number(row.phaseNum) || 0
    return sum + (price * quantity)
  }, 0)
})

//计算总价
const formatTotal = computed(() => {
  return `¥${totalAmount.value.toFixed(2)}`
})


//弹窗的处理
let PopupsPageNo=ref(1)
let PopupsPageSize=ref(10)
const selectedCount = ref(0)
const totalItems = ref(0)
const dialogVisible = ref(false)
const currentSelected = ref(null)//当前选中
const selectedRows = ref([]) // 多选时使用
const searchForm = reactive({
  code: '',
})

// 表格选择处理
const handleSelectionChange = (selection:any) => {
  selectedRows.value = selection
  selectedCount.value = selection.length
  if (selection.length > 0) {
    currentSelected.value = selection[0]
  } else {
    currentSelected.value = null
  }
}



const clearSelection = () => {

}

//分页方法
let handlePageChange=()=>{

}




let addDetailRow = () => {
  inventoryCheckDetail.value.push({
    id: generateUUID(),
    inventoryCheckCode:'',
    goodId:0,
    goodsCode:'',
    stock:0,
    goodsName:'',
    unit:'',
    checkNum:0,
    phaseNum:0,
    singleCost:0,
    sumCost:0,
    isDelete:0,
    createId:1,
    createDate:new Date(),
    updateId:1,
    updateDate:new Date()
  })
}

let addProfitDetail=async(inventoryProfitCode:string)=>{
  for (const item of inventoryProfitDetail.value) {
    let response= await request({
      url:'kc/inventoryProfitDetail/insertInventoryProfitDetail',
      method:'post',
      data :{
        ...item,
        inventoryProfitCode:inventoryProfitCode
      }
    })
  }
}

let addLossDetail=async(inventoryLossCode:string)=>{
  for (const item of inventoryLossDetail.value) {
    let response= await request({
      url:'kc/inventoryLossDetail/insertInventoryLossDetail',
      method:'post',
      data :{
        ...item,
        inventoryLossCode:inventoryLossCode
      }
    })

  }
}

let insertInventoryProfitOrder =async()=>{

  // outStoreOrder.value.sourceCode=sourceCode.value
  let response =await request.post('kc/inventoryProfit/insertInventoryProfit',{
        ...inventoryProfitOrder.value,
      },
  )
  await addProfitDetail(inventoryProfitOrder.value.code)
  if(response.data.code==200){

    let response1 = request.post('workflowDesign/workFlow/startProcess',{
          code:inventoryProfitOrder.value.code,
          type:42,
        },
    )
    ElMessage.success('已生成盘盈单')
  }else{
    ElMessage.error('生成盘盈单失败')
  }

}

let insertInventoryLossOrder =async()=>{

  // outStoreOrder.value.sourceCode=sourceCode.value
  let response =await request.post('kc/inventoryLoss/insertInventoryLoss',{
        ...inventoryLossOrder.value,
      },
  )
  await addLossDetail(inventoryLossOrder.value.code)
  if(response.data.code==200){

    let response1 = request.post('workflowDesign/workFlow/startProcess',{
          code:inventoryLossOrder.value.code,
          type:41,
        },
    )
    ElMessage.success('已生成盘亏单')
  }else{
    ElMessage.error('生成盘亏单失败')
  }

}



const formRef = ref<FormInstance>();

let insertInventoryCheckOrder =async()=>{
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请填写完整基本信息');
      return;
    }

    await addDetail(inventoryCheckOrder.value.code)

    //有盘盈数据
    if (inventoryProfitDetail.value.length > 0) {

      let response = await request.post('xs/counter/addCode', {docType: 'PYD'})
      inventoryProfitOrder.value.code = response.data.data
      inventoryCheckOrder.value.inventoryProfitCode = response.data.data
      inventoryProfitOrder.value.deptId = inventoryCheckOrder.value.deptId
      inventoryProfitOrder.value.storeId = inventoryCheckOrder.value.storeId
      inventoryProfitOrder.value.checkManId = inventoryCheckOrder.value.checkManId
      await insertInventoryProfitOrder()
    }
    //有盘亏数据
    if (inventoryLossDetail.value.length > 0) {

      let response = await request.post('xs/counter/addCode', {docType: 'PKD'})
      inventoryLossOrder.value.code = response.data.data
      inventoryCheckOrder.value.inventoryLossCode = response.data.data
      inventoryLossOrder.value.deptId = inventoryCheckOrder.value.deptId
      inventoryLossOrder.value.storeId = inventoryCheckOrder.value.storeId
      inventoryLossOrder.value.checkManId = inventoryCheckOrder.value.checkManId
      await insertInventoryLossOrder()
    }

    let response = await request.post('kc/inventoryCheck/insertInventoryCheck', {
          ...inventoryCheckOrder.value,
        },
    )

    if (response.data.code == 200) {
      let response1 = request.post('workflowDesign/workFlow/startProcess', {
            code: inventoryCheckOrder.value.code,
            type: 8,
          },
      )
      ElMessage.success('增加成功')
      router.replace('/home/inventoryCheck/page')
    } else {
      ElMessage.error('增加失败')
    }
  })
}



</script>


<style scoped>
.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.required-label::after {
  content: "*";
  color: #f56c6c;
  margin-left: 4px;
}

.goods-table {
  margin-top: 20px;
}

.toolbar {
  margin-bottom: 15px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.el-table :deep(.el-input__inner) {
  text-align: center;
}
.total-summary {
  background: #fff8dc; /* 浅黄色背景 */
  padding: 12px 20px;
  display: flex;
  justify-content: flex-end;
  border: 1px solid #ebeef5;
  border-top: none;
}

.total-label {
  font-weight: 600;
  color: #606266;
  margin-right: 30px;
}

.total-amount {
  color: #f56c6c;
  min-width: 120px;
  text-align: right;
  font-family: Arial, sans-serif;
}
.pagination-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
.dialog-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
}

.date-label {
  color: #606266;
  margin: 0 10px;
}

.date-separator {
  margin: 0 8px;
  color: #c0c4cc;
}

.selected-info {
  margin: 12px 0;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.pagination-info {
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 15px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
}


</style>
